<template>
    <el-dialog v-model="dialogVisible" :title="'编辑帖子'" width="600px" top="5vh" align-center>
        <div class="post-edit-container">
            <!-- 内容编辑 -->
            <div class="edit-content">
                <el-input v-model="editContent" type="textarea" :rows="4" placeholder="编辑帖子内容..." maxlength="500"
                    show-word-limit resize="none" class="content-input" />
            </div>

            <!-- 图片预览 -->
            <div v-if="editImages.length > 0" class="image-preview">
                <div v-for="(image, index) in editImages" :key="index" class="image-item">
                    <img :src="image.url" alt="预览图片" @click="previewImages(index)" />
                    <div class="image-actions">
                        <el-icon @click="removeImage(index)">
                            <Close />
                        </el-icon>
                    </div>
                </div>
            </div>

            <!-- 操作栏 -->
            <div class="edit-actions">
                <div class="action-buttons">
                    <el-tooltip content="添加图片" placement="top">
                        <el-button text @click="triggerImageUpload">
                            <el-icon>
                                <Picture />
                            </el-icon>
                        </el-button>
                    </el-tooltip>
                </div>
            </div>

            <!-- 隐藏的文件输入 -->
            <input ref="fileInput" type="file" multiple accept="image/*" @change="handleImageSelect"
                style="display: none" />
        </div>

        <template #footer>
            <div class="dialog-actions">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="submitting" @click="handleSubmit" :disabled="!editContent.trim()">
                    保存修改
                </el-button>
            </div>
        </template>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="imagePreviewVisible" :title="`图片 ${currentImageIndex + 1} / ${editImages.length}`"
            width="80%" top="5vh" align-center>
            <div class="image-preview-container">
                <img :src="currentImageUrl" alt="预览图片" class="preview-image" />
                <div class="preview-actions">
                    <el-button @click="prevImage" :disabled="currentImageIndex === 0">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        上一张
                    </el-button>
                    <el-button @click="nextImage" :disabled="currentImageIndex === editImages.length - 1">
                        下一张
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </el-button>
                    <el-button type="primary" @click="imagePreviewVisible = false">
                        关闭
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { useCirclePostsStore } from '@/stores/circle_posts'

const circlePostsStore = useCirclePostsStore()

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    post: {
        type: Object,
        default: null
    }
})

const emit = defineEmits(['update:visible', 'success'])

// 对话框显示状态
const dialogVisible = ref(false)

// 编辑数据
const editContent = ref('')
const editImages = ref([])
const submitting = ref(false)
const fileInput = ref(null)

// 图片预览相关
const imagePreviewVisible = ref(false)
const currentImageIndex = ref(0)
const currentImageUrl = computed(() => editImages.value[currentImageIndex.value]?.url || '')

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
    dialogVisible.value = newVal
    if (newVal && props.post) {
        initEditData()
    }
})

// 监听对话框状态变化
watch(dialogVisible, (newVal) => {
    emit('update:visible', newVal)
})

// 初始化编辑数据
const initEditData = () => {
    if (!props.post) return

    editContent.value = props.post.content || ''

    // 初始化图片预览
    editImages.value = []
    if (props.post.images && props.post.images !== 'null') {
        const imagesArray = props.post.images.split(',').filter(img => img.trim())
        editImages.value = imagesArray.map(url => ({
            url: url.trim(),
            file: null,
            uploading: false
        }))
    }
}

// 图片预览功能
const previewImages = (index) => {
    currentImageIndex.value = index
    imagePreviewVisible.value = true
}

const prevImage = () => {
    if (currentImageIndex.value > 0) {
        currentImageIndex.value--
    }
}

const nextImage = () => {
    if (currentImageIndex.value < editImages.value.length - 1) {
        currentImageIndex.value++
    }
}

const triggerImageUpload = () => {
    fileInput.value.click()
}

const handleImageSelect = async (event) => {
    const files = Array.from(event.target.files)
    if (files.length + editImages.value.length > 9) {
        ElMessage.warning('最多只能上传9张图片')
        return
    }

    for (const file of files) {
        try {
            const url = URL.createObjectURL(file)
            const newImage = {
                url,
                file,
                uploading: true
            }
            editImages.value.push(newImage)

            const response = await circlePostsStore.uploadCirclePostImage(file)
            if (response.code === 0) {
                const imageIndex = editImages.value.findIndex(img => img.url === url)
                if (imageIndex !== -1) {
                    URL.revokeObjectURL(url)
                    editImages.value[imageIndex].url = response.data.url
                    editImages.value[imageIndex].uploading = false
                }
            } else {
                throw new Error(response.msg)
            }
        } catch (error) {
            console.error('图片上传失败:', error)
            ElMessage.error('图片上传失败')
            const failedIndex = editImages.value.findIndex(img => img.uploading)
            if (failedIndex !== -1) {
                const failedImage = editImages.value[failedIndex]
                URL.revokeObjectURL(failedImage.url)
                editImages.value.splice(failedIndex, 1)
            }
        }
    }

    event.target.value = ''
}

const removeImage = (index) => {
    if (index >= 0 && index < editImages.value.length) {
        const image = editImages.value[index]
        if (image.url.startsWith('blob:')) {
            URL.revokeObjectURL(image.url)
        }
        editImages.value.splice(index, 1)
    }
}

// 提交编辑
const handleSubmit = async () => {
    if (!editContent.value.trim()) {
        ElMessage.warning('请输入帖子内容')
        return
    }

    if (!props.post) {
        ElMessage.error('帖子数据错误')
        return
    }

    submitting.value = true

    try {
        // 等待所有图片上传完成
        const uploadingImages = editImages.value.filter(img => img.uploading)
        if (uploadingImages.length > 0) {
            ElMessage.warning('请等待图片上传完成')
            submitting.value = false
            return
        }

        const updateData = {
            content: editContent.value.trim()
        }

        // 处理图片 - 保持为数组格式
        if (editImages.value.length > 0) {
            // 提取所有图片的URL并过滤空值，保持为数组格式
            const imageUrls = editImages.value.map(img => img.url).filter(url => url && url.trim())
            if (imageUrls.length > 0) {
                // 保持为数组格式
                updateData.images = imageUrls
            }
        } else {
            // 如果没有图片，设置为空数组
            updateData.images = []
        }

        const result = await circlePostsStore.updatePostAction(props.post.post_id, updateData)
        if (result && result.code === 0) {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            emit('success')
        } else {
            throw new Error(result?.msg || '修改失败')
        }
    } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败：' + error.message)
    } finally {
        submitting.value = false
    }
}
</script>

<style scoped>
.post-edit-container {
    padding: 0 4px;
}

.edit-content {
    margin-bottom: 20px;
}

.content-input {
    width: 100%;
}

:deep(.content-input .el-textarea__inner) {
    font-size: 14px;
    line-height: 1.5;
}

.image-preview {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-bottom: 16px;
}

.image-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: 6px;
    overflow: hidden;
    background: #f5f7fa;
}

.image-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
    transition: transform 0.2s;
}

.image-item img:hover {
    transform: scale(1.05);
}

.image-actions {
    position: absolute;
    top: 4px;
    right: 4px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    font-size: 12px;
}

.edit-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

:deep(.action-buttons .el-button) {
    padding: 8px;
}

.dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 图片预览样式 */
.image-preview-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.preview-image {
    max-width: 100%;
    max-height: 70vh;
    object-fit: contain;
    border-radius: 8px;
}

.preview-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .image-preview {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>